package com.woniu.service.impl;

import com.woniu.entity.InpatientRecord;
import com.woniu.mapper.InpatientRecordMapper;
import com.woniu.service.ScheduledTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
@EnableScheduling
@Slf4j
public class ScheduledTaskServiceImpl implements ScheduledTaskService {
    // 余额提醒阈值 (例如 500 元)
    private static final BigDecimal LOW_BALANCE_THRESHOLD = new BigDecimal("500.00");
    @Resource
    private InpatientRecordMapper recordMapper;
    // 每日床位费自动扣款,设置每天凌晨 1:00 执行
    @Scheduled(cron = "0 0 1 * * ?") // Cron 表达式：秒 分 时 日 月 周
    @Transactional(rollbackFor = Exception.class)
    public void performDailyBedFeeDeduction() {
        log.info("【定时任务】开始执行：每日床位费扣款...");
        try {
            //批量扣除所有在院病人的每日床位费
            Integer count = recordMapper.deductDailyBedFees();
            log.info("【定时任务】床位费扣款完成，共影响 {} 条住院记录", count);
        } catch (Exception e) {
            log.error("【定时任务】床位费扣款失败", e);
        }
    }
    // 每日押金余额不足提醒,早上 8:00 执行 (在扣完床位费之后)
    @Scheduled(cron = "0 0 8 * * ?")
    public void checkForLowBalance() {
        log.info("【定时任务】开始执行：检查押金余额不足...");
        try {
            //查询余额低于阈值的所有在院病人
            List<InpatientRecord> lowBalancePatients =
                    recordMapper.findLowBalanceInpatients(LOW_BALANCE_THRESHOLD); //

            if (lowBalancePatients.isEmpty()) {
                log.info("【定时任务】所有在院患者押金充足。");
                return;
            }

            log.warn("【定时任务】发现 {} 位患者押金余额不足 (低于 {} 元)",
                    lowBalancePatients.size(), LOW_BALANCE_THRESHOLD);

            for (InpatientRecord record : lowBalancePatients) {
                // 在这里发送通知给护士站

                log.warn("  -> [通知护士站] 患者ID: {}, 剩余余额: {}",
                        record.getHzCaseId(), record.getHzBalance());
            }

        } catch (Exception e) {
            log.error("【定时任务】检查押金余额失败", e);
        }
    }
}
